import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/modules/user.js'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      component: () => import('@/views/login/LonginPage.vue'),
      meta: { requiresGuest: true } // 添加元信息，标识游客页面
    },
    {
      path: '/share/:identifier',
      component: () => import('@/views/share/ShareSimplePage.vue')
    },
    {
      path: '/share/404',
      component: () => import('@/views/share/NotFoundPage.vue')
    },
    {
      path: '/',
      redirect: '/home',
      component: () => import('@/views/layout/LayoutContainer.vue'),
      meta: { requiresAuth: true }, // 添加元信息，标识需要认证
      children: [
        {
          path: '/home',
          component: () => import('@/views/home/HomePage.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: '/recycle',
          component: () => import('@/views/recycle/RecyclePage.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: '/shares',
          component: () => import('@/views/share/SharesPage.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: '/admin',
          component: () => import('@/views/admin/AdminPage.vue'),
          meta: { requiresAuth: true }
        }
      ]
    }
  ]
})

router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  const hasToken = userStore.token

  // 访问需要认证的页面,但没有token
  if (to.meta.requiresAuth && !hasToken) {
    return next('/login')
  }

  // 访问游客页面,但已有token
  if (to.meta.requiresGuest && hasToken) {
    return next('/')
  }

  // 其他情况正常放行
  next()
})

export default router
